package org.romzzz.gwtclassifieds.client.ui;

import org.romzzz.gwtclassifieds.client.data.ClassifiedBean;
import org.romzzz.gwtclassifieds.client.i18n.LocalizedStrings;

import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.ui.HTML;

/**
 * This panel displays the classified at the bottom right.
 */
public class ClassifiedDetails extends ContentPanel {
	
	public ClassifiedDetails() {
		super(new FitLayout());
		setHeaderVisible(true);
		addStyleName("detailsPanel");
	}
	
	/**
	 * This method is used by {@link ClassifiedGrid ClassifiedGrid} to set which classified will be displayed.
	 * 
	 * @param classified the classified to display (gwt bean)
	 */
	public void setContent(ClassifiedBean classified) {
		clear();
		setHeading(classified.getTitle());
		add(getHTMLDisplay(classified));
		layout();
	}
	
	/**
	 * Empty the panel.
	 */
	public void clear() {
		setHeading("&nbsp;");
		removeAll();
	}
	
	/**
	 * Get HTML formatted display of the classified bean.
	 * 
	 * @param classified the bean
	 * @return formatted HTML
	 */
	private HTML getHTMLDisplay(ClassifiedBean classified) {
		LocalizedStrings localizedStrings = GWT.create(LocalizedStrings.class);
		StringBuilder sb = new StringBuilder();
		sb.append("<table cellspacing='2'><tbody>");
		sb.append("<tr><td class='detailsTableTitle'>").append(localizedStrings.type()).append("</td><td>").append(classified.isOffer().booleanValue() ? localizedStrings.offer() : localizedStrings.seek()).append("</td></tr>");
		sb.append("<tr><td class='detailsTableTitle'>").append(localizedStrings.date()).append("</td><td>").append(DateTimeFormat.getFormat("d.M.y").format(classified.getDate())).append("</td></tr>");
		sb.append("<tr><td class='detailsTableTitle'>").append(localizedStrings.category()).append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td><td>").append(classified.getCategory()).append("</td></tr>");
		String contact = classified.getContact();
		if (contact != null && contact.contains("@")) {
			contact = "<a href=mailto:" + contact + ">" + contact + "</a>";
		}
		sb.append("<tr><td class='detailsTableTitle'>Contact</td><td>").append(contact).append("</td></tr>");
		sb.append("</tbody></table>");
		sb.append("<hr />").append("<p>").append(classified.getBody()).append("</p>");
		return new HTML(sb.toString());
	}

}
